import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
import { tbactivityfielddata } from '../../../atoms/db';

const logger = anylogger('pages/api/activity/fielddatasave.api');

export type Result = {
	ok: boolean;
	message: string;
};

export type Message = {
	aid: string;
	data: ITbactivityfielddata[];
};

/**
 * 活动报名信息字段-保存
 */
const handler = an48<Result>();

handler.post(async (req, res) => {
	try {
		logger.debug('msg body:', req.body);
		const { aid, data } = req.body as Message;
		if (aid && data && data.length > 0) {
			//删除
			await tbactivityfielddata().del().where({ aid });
			//插入
			const d = data.map((it) => {
				return {
					aid,
					...it
				};
			});
			await tbactivityfielddata().insert(d);
		}
		res.status(200).json({ ok: true, message: '' });
	} catch (error) {
		logger.error(error);
		logger.trace(error);
		res.status(200).json({ ok: false, message: (error as Error).message });
	}
});

export const config = {} as PageConfig;

export default handler;
